<?php
namespace App\Servers\WebSocket\Utils;

class Factory
{
    private static $instance;
    private $invokeClass = [];
    public static function getInstance(): Factory
    {
        if (!self::$instance) {
            self::$instance = new self();
        }
        return self::$instance;
    }

    // 
    /**
     * 分发消息，到指定处理类
     *
     * @param [type] $data 前端发送的数据
     * @param [type] $fd  套接字
     * @return string
     */
    public function dispatch($data,$container,$fd): string
    {
        if (!isset($data->scope) || count(explode('-', $data->scope)) != 2) {
            return Response::getInstance()->error('unkown', 4000, '参数错误:scope')->end();
        }
        $scopes = explode('-', $data->scope);
        $className = ucfirst($scopes[1]) . ucfirst($scopes[0]);
        if (!isset($this->invokeClass[$className])) {
            $fullClassName = 'App\\Servers\\WebSockets\\Logics\\' . $className;
            if (!class_exists($fullClassName)) {
                return Response::getInstance()->data($scopes,['msg'=>'未知操作','code'=>1000,'data'=>$data])->end();
            }
            $this->invokeClass[$className] = new $fullClassName($container);
        }
        return $this->invokeClass[$className]->handle($data,$fd);
    }
}